import os
import subprocess
import gtk
import pexpect
import string
from DlgPassword import DlgPassword

class Deployer:
    def __init__( self, wizard, outputwin):
        self.__wiz = wizard
        self.__outputWin = outputwin


    def __copySourceDirContents2Dest( self, fromdir, todir, linkdir):
        if os.path.isdir( todir):
            isCopyDone = False
            tagDone = "__COPY_DONE__"
            cmd = "cp -Rpv " + fromdir + "/* " + todir + " && echo " + tagDone
            try:
                proc = subprocess.Popen( cmd, shell=True
                                       , stdin=subprocess.PIPE
                                       , stdout=subprocess.PIPE
                                       , stderr=subprocess.STDOUT) # send errors to stdout
                data = proc.stdout.readline()
                self.__outputWin.appendText( "\n\n\n--> Copying files...\n\n")
                while data != "":
                    if string.find( data, tagDone) == -1:
                        filePath = data.split()[ 2]
                        filePath = filePath[1: 1 + len( filePath) - 2] #without "`" and "'"
                        data = proc.stdout.readline()
                        self.__outputWin.appendText( filePath + "\n")
                    else:
                        isCopyDone = True
                        break

            except OSError, e:
                msg = "Attempt to copy files has been failed!\ncommand: [%s]\nOS errno: [%d]\nerror: %s" % (cmd, e.errno, e.strerror) 
                dlg = gtk.MessageDialog( None, 0,
                                        gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
                                        msg);
                dlg.run()
                dlg.destroy()

            if isCopyDone:
                dirSplited = os.path.split( todir)
                cmd = "cd " + dirSplited[ 0] + "&& ln -s " + dirSplited[ 1] + " " + linkdir 
                proc = subprocess.Popen( cmd, shell=True
                                       , stdin=subprocess.PIPE
                                       , stdout=subprocess.PIPE
                                       , stderr=subprocess.STDOUT) # send errors to stdout
                stdout = proc.communicate()[ 0]
                self.__outputWin.appendText( repr( stdout) + "\n")
                self.__outputWin.appendText( "\n\n=*=*= DEPLOY COMPLETED =*=*=\n")
            else:
                self.__outputWin.appendText( "\n\n=*=*= COPY HAS BEEN FAILED !!! =*=*=\n")

        
    def deploy( self, info):
        if len( info) > 0:
            try:
                os.makedirs( info[ "toDir"])
                #child = pexpect.spawn( "su -")
                #i = child.expect( ["Password:.*", pexpect.EOF])
                #if i == 0:        
                #    child.sendline( info[ "rootpassword"])
                #    i = child.expect( ["root", pexpect.EOF])
                #    if i == 0:
                #        toDirName = os.path.split( info[ "toDir"])
                #        cmd = "mkdir " + info[ "toDir"]
                #            #+ "; chmod a+wr " + info[ "toDir"]
                #            #+ "; ln -s ./" + toDirName[ 1] + " " + info[ "linkdirname"]
                #        child.sendline( cmd)
                #        i = child.expect( ["", pexpect.EOF])
                #        if i == 0:
                #            child.sendline( "exit")
                #            self.__copySourceDirContents2Dest( info[ "fromDir"], info[ "toDir"])

                self.__copySourceDirContents2Dest( info[ "fromDir"], info[ "toDir"], info[ "linkdirname"])

            except OSError, e:
                msg = "Attempt to create dir [%s] has been failed!\nOS errno: [%d]\nerror: %s" % (info[ "toDir"], e.errno, e.strerror) 
                dlg = gtk.MessageDialog( None, 0,
                                        gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
                                        msg);
                dlg.run()
                dlg.destroy()


    def getRootPassword( self):
        password = ""
        dlg = DlgPassword( self.__wiz)
        response = dlg.run()
        if response == gtk.RESPONSE_OK:
            password = dlg.getPassword()

        return password

